"""
Contains any filter functions used in packagemapWriter
"""
from types import *
import os
from regexpPredicate import *
    

def makeFilter(aList):
    """
    Makes a filter function, i.e. a boolean function for a string, out of a list of types.
    Currently three types of things can be in the list:
    
    * strings - strings are compiled to a predicate regular expression functions, so all strings must be a regular expression, following the re module
    * compiled regular expression - any compiled regular expression is converted to a predicate regular expression function
    * one argument boolean functions - argument length cannot be checked 
    """
    compiledFilters = []
    for aFilter in aList:
        if isinstance(aFilter, basestring):
            compiledFilters.append(REPredicate.fromString(aFilter))
        elif isinstance(aFilter, CompiledREType):
            compiledFilters.append(REPredicate(aFilter))
        elif isinstance(aFilter, FunctionType):
            compiledFilters.append(aFilter)
        else:
            raise TypeError, "makeFilter can only take RE strings, compiled REs, or predicates as items in the list"
    return lambda aString: not False in map(lambda x: bool(x(aString)), compiledFilters)

class ListFilter(list):
    def __init__(self, theFilter, val):
        if isinstance(theFilter, list):
            val = filter(makeFilter(theFilter), val)
        else:
            val = filter(theFilter, val)
        list.__init__(self, val)
            

def fileFilter(fileList):
    #Filters should be for relative paths (do not use REs from the start of the string)
    return ListFilter(["~$", #emacs buffer files
                       ".svn" + os.sep, #svn files
                       "README$", #text files are not included in a packagemap
                       "LICENSE$",
                       "TODO$",
                       "INSTALL$",
                       "CREDITS$",
                       ".txt$",
                       ".pdf$",
                       ".doc$"], fileList)
